/**
 * ILOVEFREE 搜索引擎切换功能
 * 实现8个��索引擎的动态切换和搜索功能
 */

class IlovefreeSearch {
    constructor() {
        this.currentEngine = 'baidu';
        this.searchHistory = [];
        this.maxHistoryItems = 10;
        this.init();
    }

    init() {
        this.bindEvents();
        this.setupSearchForm();
        this.setupKeyboardShortcuts();
        this.loadSearchHistory();
    }

    bindEvents() {
        // 搜索引擎切换按钮
        const toggleBtn = document.getElementById('searchEngineToggle');
        const dropdown = document.getElementById('searchEngineDropdown');
        const options = document.querySelectorAll('.search-engine-option');

        if (toggleBtn && dropdown) {
            // 切换下拉菜单显示/隐藏
            toggleBtn.addEventListener('click', (e) => {
                e.preventDefault();
                e.stopPropagation();
                this.toggleDropdown();
            });

            // 选择搜索引擎
            options.forEach(option => {
                option.addEventListener('click', (e) => {
                    e.preventDefault();
                    e.stopPropagation();
                    this.selectSearchEngine(option);
                });
            });

            // 点击外部关闭下拉菜单
            document.addEventListener('click', (e) => {
                if (!dropdown.contains(e.target) && !toggleBtn.contains(e.target)) {
                    this.hideDropdown();
                }
            });
        }

        // 搜索输入框事件
        const searchInput = document.getElementById('searchInput');
        if (searchInput) {
            searchInput.addEventListener('keypress', (e) => {
                if (e.key === 'Enter') {
                    this.performSearch();
                }
            });

            // 输入框聚焦效果
            // searchInput.addEventListener('focus', () => {
            //     searchInput.parentElement.parentElement.classList.add('focused');
            // });

            // searchInput.addEventListener('blur', () => {
            //     searchInput.parentElement.parentElement.classList.remove('focused');
            // });
        }
    }

    setupSearchForm() {
        const searchForm = document.getElementById('searchForm');
        if (searchForm) {
            searchForm.addEventListener('submit', (e) => {
                const searchInput = document.getElementById('searchInput');
                const searchTerm = searchInput.value.trim();

                if (!searchTerm) {
                    e.preventDefault();
                    // searchInput.focus();
                    return false;
                }

                // 让表单正常提交，不需要额外的处理
                this.trackSearch(this.currentEngine, searchTerm);
            });
        }
    }

    setupKeyboardShortcuts() {
        // 快捷键支持
        document.addEventListener('keydown', (e) => {
            // Ctrl/Cmd + K 聚焦搜索框
            if ((e.ctrlKey || e.metaKey) && e.key === 'k') {
                e.preventDefault();
                const searchInput = document.getElementById('searchInput');
                if (searchInput) {
                    // searchInput.focus();
                    searchInput.select();
                }
            }

            // ESC 关闭下拉菜单
            if (e.key === 'Escape') {
                this.hideDropdown();
            }
        });
    }

    toggleDropdown() {
        const dropdown = document.getElementById('searchEngineDropdown');
        if (dropdown) {
            if (dropdown.classList.contains('show')) {
                this.hideDropdown();
            } else {
                this.showDropdown();
            }
        }
    }

    showDropdown() {
        const dropdown = document.getElementById('searchEngineDropdown');
        const toggleBtn = document.getElementById('searchEngineToggle');

        if (dropdown) {
            dropdown.classList.add('show');
            if (toggleBtn) {
                toggleBtn.classList.add('active');
            }
        }
    }

    hideDropdown() {
        const dropdown = document.getElementById('searchEngineDropdown');
        const toggleBtn = document.getElementById('searchEngineToggle');

        if (dropdown) {
            dropdown.classList.remove('show');
            if (toggleBtn) {
                toggleBtn.classList.remove('active');
            }
        }
    }

    selectSearchEngine(option) {
        if (!option) return;

        // 获取搜索引擎信息
        const engine = option.dataset.engine;
        const action = option.dataset.action;
        const name = option.dataset.name;
        const engineName = option.querySelector('span').textContent;

        // 更新当前搜索引擎
        this.currentEngine = engine;

        // 更新显示的搜索引擎名称
        const currentEngineSpan = document.getElementById('currentSearchEngine');
        if (currentEngineSpan) {
            currentEngineSpan.textContent = engineName;
        }

        // 更新表单action和input name
        const searchForm = document.getElementById('searchForm');
        const searchInput = document.getElementById('searchInput');

        if (searchForm && action) {
            searchForm.action = action;
        }

        if (searchInput && name) {
            searchInput.name = name;
        }

        // 更新选项的active状态
        const options = document.querySelectorAll('.search-engine-option');
        options.forEach(opt => {
            opt.classList.remove('active');
        });
        option.classList.add('active');

        // 关闭下拉菜单
        this.hideDropdown();

        // 聚焦到搜索输入框
        if (searchInput) {
            // searchInput.focus();
        }

        // 保存用户选择到localStorage
        this.saveSearchEnginePreference(engine);
    }

    performSearch() {
        const searchInput = document.getElementById('searchInput');
        const searchForm = document.getElementById('searchForm');

        if (!searchInput || !searchForm) return;

        const searchTerm = searchInput.value.trim();
        if (!searchTerm) {
            // searchInput.focus();
            return;
        }

        // 添加搜索统计
        this.trackSearch(this.currentEngine, searchTerm);

        // 打开新窗口进行搜索（避免重复提交）
        const searchUrl = `${searchForm.action}?${searchInput.name}=${encodeURIComponent(searchTerm)}`;
        window.open(searchUrl, '_blank');
    }

    saveSearchEnginePreference(engine) {
        try {
            localStorage.setItem('ilovefree_preferred_search_engine', engine);
        } catch (e) {
            console.warn('无法保存搜索引擎偏好:', e);
        }
    }

    loadSearchEnginePreference() {
        try {
            const saved = localStorage.getItem('ilovefree_preferred_search_engine');
            if (saved) {
                const option = document.querySelector(`[data-engine="${saved}"]`);
                if (option) {
                    this.selectSearchEngine(option);
                }
            }
        } catch (e) {
            console.warn('无法加载搜索引擎偏好:', e);
        }
    }

    trackSearch(engine, searchTerm) {
        // 添加到搜索历史
        this.addToSearchHistory(searchTerm);

        // 这里可以添加搜索统计功能
        console.log(`使用 ${engine} 搜索: ${searchTerm}`);

        // 可以发送到统计服务
        if (typeof gtag !== 'undefined') {
            gtag('event', 'search', {
                'search_engine': engine,
                'search_term': searchTerm
            });
        }
    }

    loadSearchHistory() {
        try {
            const saved = localStorage.getItem('ilovefree_search_history');
            if (saved) {
                this.searchHistory = JSON.parse(saved);
            }
        } catch (e) {
            console.warn('无法加载搜索历史:', e);
        }
    }

    saveSearchHistory() {
        try {
            localStorage.setItem('ilovefree_search_history', JSON.stringify(this.searchHistory));
        } catch (e) {
            console.warn('无法保存搜索历史:', e);
        }
    }

    addToSearchHistory(searchTerm) {
        // 移除重复项
        this.searchHistory = this.searchHistory.filter(item => item !== searchTerm);

        // 添加到开头
        this.searchHistory.unshift(searchTerm);

        // 限制历史记录数量
        if (this.searchHistory.length > this.maxHistoryItems) {
            this.searchHistory = this.searchHistory.slice(0, this.maxHistoryItems);
        }

        this.saveSearchHistory();
    }

    clearSearchHistory() {
        this.searchHistory = [];
        this.saveSearchHistory();
    }

    // 获取搜索引擎图标URL
    getSearchEngineIcon(engine) {
        const icons = {
            'baidu': 'data:image/svg+xml,<svg xmlns="http://www.w3.org/2000/svg" viewBox="0 0 24 24"><circle cx="12" cy="12" r="10" fill="%233B83FF"/></svg>',
            'sogou': 'data:image/svg+xml,<svg xmlns="http://www.w3.org/2000/svg" viewBox="0 0 24 24"><circle cx="12" cy="12" r="10" fill="%23FB6E0A"/></svg>',
            'bing': 'data:image/svg+xml,<svg xmlns="http://www.w3.org/2000/svg" viewBox="0 0 24 24"><circle cx="12" cy="12" r="10" fill="%2300883F"/></svg>',
            '360': 'data:image/svg+xml,<svg xmlns="http://www.w3.org/2000/svg" viewBox="0 0 24 24"><circle cx="12" cy="12" r="10" fill="%237B1FF2"/></svg>',
            'google': 'data:image/svg+xml,<svg xmlns="http://www.w3.org/2000/svg" viewBox="0 0 24 24"><circle cx="12" cy="12" r="10" fill="%23EA4335"/></svg>',
            'wangpan': 'data:image/svg+xml,<svg xmlns="http://www.w3.org/2000/svg" viewBox="0 0 24 24"><circle cx="12" cy="12" r="10" fill="%23FF6B35"/></svg>',
            'yingshi': 'data:image/svg+xml,<svg xmlns="http://www.w3.org/2000/svg" viewBox="0 0 24 24"><circle cx="12" cy="12" r="10" fill="%23E91E63"/></svg>',
            'youhui': 'data:image/svg+xml,<svg xmlns="http://www.w3.org/2000/svg" viewBox="0 0 24 24"><circle cx="12" cy="12" r="10" fill="%23FF9800"/></svg>'
        };
        return icons[engine] || icons['baidu'];
    }

    // 响应式处理
    handleResponsive() {
        const isMobile = window.innerWidth <= 480;
        const dropdown = document.getElementById('searchEngineDropdown');
        const toggleBtn = document.getElementById('searchEngineToggle');

        if (isMobile && dropdown && toggleBtn) {
            // 移动端优化：使用模态框式下拉菜单
            dropdown.style.position = 'fixed';
            dropdown.style.top = '50%';
            dropdown.style.left = '50%';
            dropdown.style.transform = 'translate(-50%, -50%)';
        } else if (dropdown) {
            // 桌面端恢复原始样式
            dropdown.style.position = '';
            dropdown.style.top = '';
            dropdown.style.left = '';
            dropdown.style.transform = '';
        }
    }
}

// 页面加载完成后初始化
document.addEventListener('DOMContentLoaded', () => {
    window.ilovefreeSearch = new IlovefreeSearch();

    // 加载用户保存的搜索引擎偏好
    window.ilovefreeSearch.loadSearchEnginePreference();

    // 处理响应式
    window.ilovefreeSearch.handleResponsive();

    // 窗口大小改变时重新处理响应式
    window.addEventListener('resize', () => {
        window.ilovefreeSearch.handleResponsive();
    });
});

// 导出类以供其他脚本使用
if (typeof module !== 'undefined' && module.exports) {
    module.exports = IlovefreeSearch;
}